package nio.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;


public class Server {
	private ServerSocketChannel serverSocketChannel;
	private Selector selector;
	private ServerSocket serverSocket;
	private  ByteBuffer sendbuffer = ByteBuffer.allocate(4096);  
	private  ByteBuffer receivebuffer = ByteBuffer.allocate(4096);  
	private  int flag = 0;  
	private static int i=0;
	public Server(){
		try {
			serverSocketChannel = ServerSocketChannel.open();
			serverSocketChannel.configureBlocking(false);
			selector = Selector.open();
			InetSocketAddress inetSocketAddress = new InetSocketAddress(5222);
			serverSocket = serverSocketChannel.socket();
			serverSocket.bind(inetSocketAddress);
			serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
			System.out.println("server start-------------");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void listen() throws IOException{
		while(true){
			selector.select();
			Set<SelectionKey>  selectionKeys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = selectionKeys.iterator();
			while(iterator.hasNext()){
				SelectionKey selectionKey = iterator.next();
				iterator.remove();
				handleKey(selectionKey);
			}
		}
	}
	
	private void handleKey(SelectionKey selectionKey) throws IOException{
		ServerSocketChannel server = null;  
        SocketChannel client = null;  
        String receiveText;  
        String sendText;  
        int count = 0 ;
        if(selectionKey.isAcceptable()){
        	server = (ServerSocketChannel)selectionKey.channel();
        	client = server.accept();
        	client.configureBlocking(false);
        	client.register(selector, selectionKey.OP_READ);
        	
        }else if(selectionKey.isReadable()){
        	 client = (SocketChannel) selectionKey.channel();  
             //将缓冲区清空以备下次读取  
             receivebuffer.clear();  
             //读取服务器发送来的数据到缓冲区中  
             count = client.read(receivebuffer);   
             if (count > 0) {  
                 receiveText = new String( receivebuffer.array(),0,count);  
                 System.out.println("客户端:"+receiveText);  
                 client.register(selector, SelectionKey.OP_WRITE);  
             }  
        } else if (selectionKey.isWritable()) {  
            //将缓冲区清空以备下次写入  
            sendbuffer.clear();  
            // 返回为之创建此键的通道。  
            client = (SocketChannel) selectionKey.channel();  
            /*sendText="message from server--" + flag++;*/
            BufferedReader strin=new BufferedReader(new InputStreamReader(System.in));
            sendText= strin.readLine();
            //向缓冲区中输入数据  
            sendbuffer.put(sendText.getBytes());  
             //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位  
            sendbuffer.flip();  
            //输出到通道  
            client.write(sendbuffer);  
           /* System.out.println("服务器端向客户端发送数据--："+sendText); */ 
            client.register(selector, SelectionKey.OP_READ);  
        }  
	}
	
	 public static void main(String[] args) throws IOException {  
	        // TODO Auto-generated method stub  
	        Server server = new Server();  
	        server.listen();  
	    }  
}
